package wangjg.mda.gen.template;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;

/**
 * 替换
 * @author wangjg
 *
 */
public class ReplaceDirective extends Directive {

	@Override
	public String getName() {
		return "replace";
	}

	@Override
	public int getType() {
		return BLOCK;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer,Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
		SimpleNode param0 = (SimpleNode) node.jjtGetChild(0);
		String regex = (String)param0.value(context);
		SimpleNode param1 = (SimpleNode) node.jjtGetChild(1);
		String replacement = (String)param1.value(context);
		
		Node bodyNode = node.jjtGetChild(2);
		StringWriter sw = new StringWriter();
		bodyNode.render(context, sw);
		String bodyStr = sw.toString();
		
//		Pattern pattern=Pattern.compile(regex, Pattern.MULTILINE|Pattern.DOTALL);
//		Matcher matcher = pattern.matcher(bodyStr);
//		bodyStr = matcher.replaceAll(replacement);
		bodyStr = bodyStr.replaceAll(regex, replacement);
		
		writer.write(bodyStr);
		return true;
	}

}